package cn.yuanqiao.archive.wenjianzhengli.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantMdataList;
import cn.yuanqiao.archive.appManager.domain.TenantYqda;
import cn.yuanqiao.archive.appManager.domain.TenantYqdaDocument;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.appManager.service.IYqdaFilePathSerive;
import cn.yuanqiao.archive.chengguojieshou.mapper.YqdaarticulatedMapper;
import cn.yuanqiao.archive.danganzhengli.utils.OfdAgent;
import cn.yuanqiao.archive.detection.util.EncryptionUtil;
import cn.yuanqiao.archive.identification.domain.IdentificationRecord;
import cn.yuanqiao.archive.identification.mapper.IdentificationRecordMapper;
import cn.yuanqiao.archive.utils.FileWaterMark;
import cn.yuanqiao.archive.webservice.utils.WebServiceFileUtils;
import cn.yuanqiao.archive.wenjianzhengli.domain.Yqdatransdoc;
import cn.yuanqiao.archive.wenjianzhengli.mapper.YqdatransdocMapper;
import cn.yuanqiao.archive.wenjianzhengli.service.ITenantYqdaDocumentService;
import cn.yuanqiao.archive.wenjianzhengli.utils.FileUploadUtils;
import cn.yuanqiao.archive.wenjianzhengli.utils.OcrUtils;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.util.BusinessBehaviorUtil;
import cn.yuanqiao.common.utils.*;
import cn.yuanqiao.common.enums.BusinessBehavior;
import cn.yuanqiao.common.util.BusinessBehaviorUtil;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static cn.yuanqiao.common.utils.PageUtils.startPage;

/**
 * @author zjj
 * @date 2023/6/28
 */
@Service
public class TenantYqdaDocumentServiceImpl implements ITenantYqdaDocumentService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${YQ.OFD.VERSION}")
    private String transType;
    @Value("${OCR_PICTURE_URL}")
    private String pictureUrl;
    @Value("${OCR_OFD_URL}")
    private String ofdUrl;
    @Value("${OCR_PDF_URL}")
    private String pdfUrl;

    @Value("${is_zt}")
    private String isZt;

    @Autowired
    private TenantCategoryMapper categoryMapper;
    @Autowired
    private TenantYqdaDocumentMapper documentMapper;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private TenantYqdaMapper yqdaMapper;
    @Autowired
    private OfdAgent ofdAgent;
    @Autowired
    private YqdatransdocMapper yqdatransdocMapper;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    TransactionDefinition transactionDefinition;
    @Autowired
    private YqdaarticulatedMapper yqdaarticulatedMapper;

    @Autowired
    private OcrUtils ocrUtils;

    @Autowired
    private IdentificationRecordMapper identificationRecordMapper;
    @Autowired
    private TenantMdataListMapper mdataListMapper;

    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;

    @Autowired
    private TenantCateMdataListMapper tenantCateMdataListMapper;

    @Autowired
    private IYqdaFilePathSerive filePathSerive;

    @Value("${identifyType}")
    private String identifyType;

    @Autowired
    private ITenantCateMdataListService tenantMdataListService;

    @Override
    @Transactional
    public JSONObject uploadFile(Long categoryId, Long daId, Integer type,String fields, MultipartFile file) throws Exception{
        LoginUser user = SecurityUtils.getLoginUser();
        String uplodPath = filePathSerive.getFilePath(categoryId);
        if(StringUtils.isEmpty(uplodPath)){
            uplodPath = sysConfigService.selectConfigByKey("YQ_MNT");
        }
        if(StringUtils.isEmpty(uplodPath)){
            throw new  ServiceException("系统参数错误YQ_MNT未找到配置！");
        }
        uplodPath = new File(uplodPath).getAbsolutePath()+File.separator;
        TenantCategory category = categoryMapper.selectTenantCategoryByID(categoryId,new TenantCategory().getTableName());
        TenantYqdaDocument document = new TenantYqdaDocument();
        document.setConTableId(daId);
        document.setTableName(category.getEfileTableName());
        String orderNoStr = documentMapper.MaxOrderNo(document);
        int orderNo =  StringUtils.isEmpty(orderNoStr) ? 1:(Integer.valueOf(orderNoStr)+1);
        String maxSize = sysConfigService.selectConfigByKey("DA_FILE_MAX");
        String extensions = sysConfigService.selectConfigByKey("DA_ALLOWED_EXTENSION");
        FileUploadUtils.setDefaultConfig(maxSize,extensions);
        TenantYqdaDocument oploadDoc = FileUploadUtils.upload(category,type,daId,orderNo,uplodPath,file);
        oploadDoc.setTableName(category.getEfileTableName());
        oploadDoc.setDocId(SnowflakeIdGenerator.generateId());
        oploadDoc.setConTableId(daId);
        oploadDoc.setCreateBy(user.getUsername());
        //获取所有的默认值插入
        TenantCategory tenantCategory = new TenantCategory();
        TenantMdataList yqdaMdataList=new TenantMdataList();
        String groupId = tenantCategoryMapper.selectGroupIdById(categoryId, tenantCategory.getTableName());
        yqdaMdataList.setGroupId(Long.valueOf(groupId));
        yqdaMdataList.setType(2);
        List<TenantMdataList> tenantMdataLists = tenantCateMdataListMapper.selectNewTenantMdataListList(yqdaMdataList);
        Map colNames=oploadDoc.getColNames();
        for(TenantMdataList tenantMdataList:tenantMdataLists){
            if(!colNames.containsKey(tenantMdataList.getFieldName().toUpperCase())){
                colNames.put(tenantMdataList.getFieldName().toUpperCase(),tenantMdataList.getDefaultValue());
            }
        }

        int r = documentMapper.insertDocument(oploadDoc);
        /*oploadDoc.setDocFileSize(oploadDoc.getColNames().get("DOC_FILE_SIZE"));
        oploadDoc.setDocFileType(oploadDoc.getColNames().get("DOC_FILE_TYPE"));
        oploadDoc.setDocName(oploadDoc.getColNames().get("DOC_NAME"));
        oploadDoc.setType(type);
        oploadDoc.setColNames(null);
        oploadDoc.setTableName(null);*/
        //更新件的电子文件数字段
        Map<String, Object> yqda = yqdaMapper.getYqdaById("ID",daId,category.getFileTableName());
        if(yqda!=null && yqda.size()>0){
            yqdaMapper.updateEfileCount(daId,"ID",1,category.getFileTableName());
            yqdaMapper.updateEfileCount(daId,"DA_ID",1,new TenantYqda().getTableName());
        }
        //不再返回实体，返回map，电子文件列表的表头不固定，根据展示字段展示数据
        TenantMdataList select = new TenantMdataList();
        select.setType(2);
        select.setIsSystem(1);
        select.setGroupId(category.getGroupId());
        List<TenantMdataList> lists = mdataListMapper.selectTenantMdataListList(select);
        StringBuilder col = new StringBuilder("DOC_ID,"+fields);
        for(TenantMdataList mdata:lists){
            col.append(","+mdata.getFieldName());
        }
        Map<String, Object> doc = documentMapper.getDocumentById(col.toString().replaceAll(",+", ","), oploadDoc.getDocId(), oploadDoc.getTableName());
        JSONObject object = new JSONObject();
        object.put("docInfo",doc);
        return object;
    }

    @Override
    public int updateDocument(JSONObject object) {
        //{"categoryId":"123","docId":"456",column:[{name:'TYPE_NAME',value:'视频'},{name:'TYPE_CODE',value:'SP'}]}
        Long categoryId = object.getLong("categoryId");
        Long docId = object.getLong("docId");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId,category.getTableName());
        JSONArray array = object.getJSONArray("column");
        Map<String,String> column = new HashMap<>();
        for (int j = 0;j<array.size();j++){
            JSONObject data = array.getJSONObject(j);
            column.put(data.getString("name"),data.getString("value"));
        }
        column.putAll(updateCommonCol(column));
        TenantYqdaDocument document = new TenantYqdaDocument();
        document.setColNames(column);
        document.setDocId(docId);
        document.setTableName(category.getEfileTableName());
        int r = documentMapper.updateDocument(document);
        return r;
    }

    @Override
    public Map<String, Object> getDocumentById(JSONObject object) {
        //{"categoryId":"123","id":"456","column":"TITLE,BGQX"}
        Long categoryId = object.getLong("categoryId");
        Long id = object.getLong("docId");
        String column = object.getString("column");
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId,category.getTableName());
        Map<String, Object> data = documentMapper.getDocumentById(column,id,category.getEfileTableName());
        return data;
    }

    @Override
    @Transactional
    public int delDocument(Long categoryId,Long[] ids,Long daId) {
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId,category.getTableName());
        //更新件的电子文件数字段
        for(int i=0;i<ids.length;i++){
            Long id = ids[i];
            TenantYqdaDocument tenantYqdaDocument1 = documentMapper.selectnameandpathbyDocid(id, category.getEfileTableName());
            Integer isDel = tenantYqdaDocument1.getIsDel();
            if(isDel==0){
                Map<String, Object> yqda = yqdaMapper.getYqdaById("ID",daId,category.getFileTableName());
                if(yqda!=null && yqda.size()>0){
                    yqdaMapper.updateEfileCount(daId,"ID",2,category.getFileTableName());
                    yqdaMapper.updateEfileCount(daId,"DA_ID",2,new TenantYqda().getTableName());
                }
            }
        }

        return documentMapper.delDocument(ids,category.getEfileTableName());
    }



    /**
     * 修改的公共字段
     * @param map
     * @return
     */
    private Map<String,String> updateCommonCol(Map<String,String> map){
        LoginUser user = SecurityUtils.getLoginUser();
        if(!map.containsKey("UPDATE_BY")){
            map.put("UPDATE_BY",user.getUsername());
        }
        if(!map.containsKey("UPDATE_TIME")){
            map.put("UPDATE_TIME", DateUtils.getTime());
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> getDocumentBydaId(JSONObject json) {
        Long categoryId=json.getLong("categoryId");
        Long daId=json.getLong("daId");

        StringBuffer fields= new StringBuffer("doc_id,TYPE,DOC_FILE_TYPE,TO_OFD ");
        if(StringUtils.isNotBlank(json.getString("fields"))){
            fields.append(" , "+json.getString("fields"));
        }
        /*String[] fieldss = fields.split(",");
        //查询必须要有TYPE字段
        Boolean bl = false;
        for(String fieldsss:fieldss){
            if("TYPE".equals(fieldsss)){
                bl = true;
                break;
            }
        }
        if(bl == false){
            fields="TYPE,"+fields;
        }*/
        String orderstr = "";
        String applyorderstr=tenantMdataListService.getorder(categoryId, json.getLong("menuId"), 2);
        if(null!=applyorderstr&&!"".equals(applyorderstr)){
            orderstr=" order by "+applyorderstr;
        }
        TenantCategory tenantCategory = categoryMapper.selectTenantCategoryByID(categoryId, new TenantCategory().getTableName());
        return documentMapper.getDocumentBydaId(fields.toString(),daId,tenantCategory.getEfileTableName(),orderstr);
    }

    @Override
    public void docToOfdTask(String tenantCode) {
        try {
            TenantCategory selectC = new TenantCategory();
            selectC.setTableName(tenantCode+ TenantCategory.BIGTABLENAME);
            List<TenantCategory> categoryList = categoryMapper.selectTenantCategoryList(selectC);
            for(TenantCategory category:categoryList){
                if(StringUtils.isNotEmpty(category.getEfileTableName())){
                    Map<String,String> map = new HashMap<>();
                    map.put("IS_DEL","0");
                    List<Map<String,Object>> list = documentMapper.getAllDoc("DOC_ID,PATH,DOC_FILE_TYPE,REAL_DOC_NAME,DOC_MNT",map,category.getEfileTableName());
                    for(Map<String,Object> docData:list){
                        File file = new File(docData.get("DOC_MNT").toString()+docData.get("PATH").toString());
                        if(file.exists()){
                            //添加转换记录
                            Yqdatransdoc yqdatransdoc = new Yqdatransdoc();
                            yqdatransdoc.setDocId((Long)docData.get("DOC_ID"));
                            yqdatransdoc.setTransType(transType);
                            yqdatransdoc.setState(0); //默认失败
                            yqdatransdoc.setTableName(tenantCode+Yqdatransdoc.BIGTABLENAME);
                            yqdatransdocMapper.insertYqdatransdoc(yqdatransdoc);
                            List<File> docFile = new ArrayList<>();
                            docFile.add(file);
                            String hz = docData.get("DOC_FILE_TYPE").toString();
                            String ofdPath = file.getParent()+File.separator+"ofd"+File.separator+file.getName().substring(0,file.getName().lastIndexOf("."))+".OFD";
                            System.out.println("ofdPath="+ofdPath);
                            if (!new File(ofdPath).getParentFile().exists()) {
                                new File(ofdPath).getParentFile().mkdirs();
                            }
                            try {
                                if("tif".equals(hz.toLowerCase())
                                        || "tiff".equals(hz.toLowerCase())
                                        || "png".equals(hz.toLowerCase())
                                        || "jpg".equals(hz.toLowerCase())){
                                    ofdAgent.imageToOFD(docFile,ofdPath);
                                }else {
                                    ofdAgent.officesToOfd(docFile,ofdPath);
                                }
                                save(yqdatransdoc.getTransId(),file.getName(),docData,category,tenantCode);
                            }catch (Exception e){
                                logger.error(e.getMessage(),e);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }

    }

    @Override
    @Transactional
    public void docToOfd(Long docId,Long categoryId) throws Exception{
        TenantCategory category = categoryMapper.selectTenantCategoryByID(categoryId,new TenantCategory().getTableName());
        Map<String, Object> docData = documentMapper.getDocumentById("DOC_ID,PATH,DOC_FILE_TYPE,REAL_DOC_NAME,DOC_MNT",docId,category.getEfileTableName());
        File file = new File(docData.get("DOC_MNT").toString()+docData.get("PATH").toString());
        if(file.exists()){
            //添加转换记录
            Yqdatransdoc yqdatransdoc = new Yqdatransdoc();
            yqdatransdoc.setDocId((Long)docData.get("DOC_ID"));
            yqdatransdoc.setTransType(transType);
            yqdatransdoc.setState(0); //默认失败
            yqdatransdocMapper.insertYqdatransdoc(yqdatransdoc);
            List<File> docFile = new ArrayList<>();
            docFile.add(file);
            String hz = docData.get("DOC_FILE_TYPE").toString();
            String ofdPath = "";
            if("OCR".equalsIgnoreCase(transType)){
                ofdPath = file.getParent()+File.separator+"pdf"+File.separator+file.getName().substring(0,file.getName().lastIndexOf("."))+".PDF";
            }else{
                ofdPath = file.getParent()+File.separator+"ofd"+File.separator+file.getName().substring(0,file.getName().lastIndexOf("."))+".OFD";
            }
            System.out.println("ofdPath="+ofdPath);
            if (!new File(ofdPath).getParentFile().exists()) {
                new File(ofdPath).getParentFile().mkdirs();
            }
            if("tif".equals(hz.toLowerCase())
                    || "tiff".equals(hz.toLowerCase())
                    || "png".equals(hz.toLowerCase())
                    || "jpg".equals(hz.toLowerCase())){
                ofdAgent.imageToOFD(docFile,ofdPath);
            }else {
                ofdAgent.officesToOfd(docFile,ofdPath);
            }
            save(yqdatransdoc.getTransId(),file.getName(),docData,category,SecurityUtils.getTenantCode());

            //添加过程信息
            String efileTableName = category.getEfileTableName();
            addBehavior(efileTableName,docId);
        }
    }

    @Transactional
    public void docToOfdHdyy(Long docId,Long categoryId) throws Exception{
        TenantCategory category = categoryMapper.selectTenantCategoryByID(categoryId,new TenantCategory().getTableName());
        Map<String, Object> docData = documentMapper.getDocumentById("DOC_ID,PATH,DOC_FILE_TYPE,REAL_DOC_NAME,DOC_MNT",docId,category.getEfileTableName());
        File file = new File(docData.get("DOC_MNT").toString()+docData.get("PATH").toString());
        if(file.exists()){
            //添加转换记录
            Yqdatransdoc yqdatransdoc = new Yqdatransdoc();
            yqdatransdoc.setDocId((Long)docData.get("DOC_ID"));
            yqdatransdoc.setTransType("hdyyofdIdentify");
            yqdatransdoc.setState(0); //默认失败
            yqdatransdocMapper.insertYqdatransdoc(yqdatransdoc);
            List<File> docFile = new ArrayList<>();
            docFile.add(file);
            String hz = docData.get("DOC_FILE_TYPE").toString();
            String ofdPath = "";
            ofdPath = file.getParent()+File.separator+"pdf"+File.separator+file.getName().substring(0,file.getName().lastIndexOf("."))+".PDF";

            System.out.println("ofdPath="+ofdPath);
            if (!new File(ofdPath).getParentFile().exists()) {
                new File(ofdPath).getParentFile().mkdirs();
            }
            if("tif".equals(hz.toLowerCase())
                    || "tiff".equals(hz.toLowerCase())
                    || "png".equals(hz.toLowerCase())
                    || "jpg".equals(hz.toLowerCase())){
                imageToOFD(docFile,ofdPath);
            }else {
                officesToOfd(docFile,ofdPath);
            }
            saveHdyy(yqdatransdoc.getTransId(),file.getName(),docData,category,SecurityUtils.getTenantCode());

            //添加过程信息
            //String efileTableName = category.getEfileTableName();
            //addBehavior(efileTableName,docId);
        }
    }

    @Async
    public void addBehavior(String efileTableName,Long docId){
        TenantYqdaDocument document = documentMapper.selectnameandpathbyDocid(docId, efileTableName);
        Long conTableId = document.getConTableId();
        BusinessBehaviorUtil.add(conTableId,BusinessBehavior.GSZH);
    }


    @Override
    public List<TenantYqdaDocument> selectNotYqdatransdoc(String filename, String houzhui) {
        String tenantCode = SecurityUtils.getTenantCode();
        List<String> eFileTable = yqdatransdocMapper.getEFileTableName(tenantCode);
        List<TenantYqdaDocument> list = new ArrayList<>();
        if(eFileTable!=null && eFileTable.size()>0){
            startPage();
            list = documentMapper.selectNotYqdatransdoc(eFileTable,new Yqdatransdoc().getTableName(),filename,houzhui);
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void identify(Long docId, Long categoryId) {
        //获取该值去验证
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        TenantCategory category = categoryMapper.selectTenantCategoryByID(categoryId, new TenantCategory().getTableName());
        Map<String, Object> docData = documentMapper.getDocumentMessageById("a.DOC_ID,a.PATH,a.DOC_FILE_TYPE,a.REAL_DOC_NAME,a.DOC_MNT,a.DOC_NAME,a.IS_IDENTIFICATION,b.DH,b.TITLE", docId, category.getEfileTableName(), category.getFileTableName());
        File file = new File(docData.get("DOC_MNT").toString() + docData.get("PATH").toString());
        String hz = docData.get("DOC_FILE_TYPE").toString().toLowerCase();
        if (docData.get("IS_IDENTIFICATION") != null && "1".equals(docData.get("IS_IDENTIFICATION").toString())) {
            throw new ServiceException("该文件已识别！");
        }
        String ocrFilesType = sysConfigService.selectConfigByKey("OCR_FILES_TYPE");
        if (StringUtils.isEmpty(ocrFilesType)) {
            throw new ServiceException("系统参数错误OCR_FILES_TYPE未找到配置！");
        }

        if ((ocrFilesType + ";").indexOf(hz + ";") < 0) {
            throw new ServiceException("该文件格式不需要识别！");
        }
        String ocrFilesSize = sysConfigService.selectConfigByKey("OCR_FILES_SIZE");
        if (StringUtils.isEmpty(ocrFilesSize)) {
            throw new ServiceException("系统参数错误OCR_FILES_SIZE未找到配置！");
        }
        if (file.exists()) {
            double size = (double) file.length() / (1024 * 1024);
            if (size > Integer.parseInt(ocrFilesSize)) {

                throw new ServiceException("文件较大无法识别！");

            }
        }
        Long maxPdfSize = 0L;
        if ("1".equals(isZt)) {
            String pdfSize = sysConfigService.selectConfigByKey("MAX_PDF_SIZE");
            if (StringUtils.isEmpty(pdfSize)) {
                throw new ServiceException("系统参数错误MAX_PDF_SIZE未找到配置！");
            }
            maxPdfSize = Long.valueOf(pdfSize) * 1024 * 1024;
        }

        try {

            //原文件
            if (file.exists()) {
                String ofdPath = file.getParent() + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd";
                //tif的存储地址
                String tifPath = file.getParent() + File.separator + "tif" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd";

                String path = docData.get("DOC_MNT").toString() + docData.get("PATH").toString();

                List<File> docFile = new ArrayList<>();
                docFile.add(file);
                IdentificationRecord identificationRecord = new IdentificationRecord();
                identificationRecord.setCreateTime(DateUtils.getNowDate());
                identificationRecord.setCreateId(SecurityUtils.getUserId());
                identificationRecord.setDocId(docId);
                identificationRecord.setFileName(docData.get("DOC_NAME").toString());
                identificationRecord.setFilePath(docData.get("PATH").toString());
                identificationRecord.setState("0");
                identificationRecord.setFilesNo(docData.get("DH") == null ? "" : docData.get("DH").toString());
                identificationRecord.setTitle(docData.get("TITLE") == null ? "" : docData.get("TITLE").toString());
                identificationRecord.setRealFileName(docData.get("REAL_DOC_NAME").toString());
                identificationRecordMapper.insertIdentificationRecord(identificationRecord);
                //获取到值去调用接口
                boolean flag1 = false;
                if ("png".equals(hz)
                        || "jpg".equals(hz)
                        || "jpeg".equals(hz)
                        || "bmp".equals(hz)) {
                    //转换  入库
                    flag1 = ocrUtils.imageToOFD(file, ofdPath, pictureUrl);
                } else if ("tiff".equals(hz) || "tif".equals(hz)) {
                    ofdAgent.imageToOFD(docFile, tifPath);
                    file = new File(tifPath);
                    flag1 = ocrUtils.officeToOFD(file, ofdPath, ofdUrl);
                } else if ("pdf".equals(hz)) {
                    if ("1".equals(isZt)) {
                        //中铁系统拿参数判断是否需要转图片
                        int count = PdfUtils.getPageCount(path);
                        if (count == 1 && file.length() > maxPdfSize) {
                            String imgPath = file.getParent() + File.separator + "img";
                            File file1 = new File(imgPath);
                            if (!file1.exists()) {
                                file1.mkdirs();
                            }
                            List<String> filePath = PdfUtils.pdf2Img(path, imgPath + File.separator);
                            //因为只有一页
                            if (filePath.size() > 0) {
                                File imgFile = new File(filePath.get(0));
                                if (imgFile.exists()) {
                                    flag1 = ocrUtils.imageToOFD(imgFile, ofdPath, pictureUrl);
                                } else {
                                    flag1 = false;
                                }
                            } else {
                                flag1 = false;
                            }
                        } else {
                            flag1 = ocrUtils.officeToOFD(file, ofdPath, ofdUrl);
                        }
                    } else {
                        flag1 = ocrUtils.officeToOFD(file, ofdPath, ofdUrl);
                    }

                } else if ("ofd".equals(hz)) {
                    flag1 = ocrUtils.officeToOFD(file, ofdPath, ofdUrl);
                }
                if (flag1) {


                    //增加识别记录
                    Long id = identificationRecord.getId();
                    IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, new IdentificationRecord().getTableName());
                    identification.setState("1");
                    identification.setTableName(identificationRecord.getTableName());
                    identification.setNewFilePath(docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd");
                    identificationRecordMapper.updateIdentificationRecord(identification);
                    //修改文件  将原文件进行修改
                    //修改电子文件表
                    File ofdFile = new File(ofdPath);
                    Path path2 = Paths.get(ofdPath);
                    BasicFileAttributes attributes = Files.readAttributes(path2, BasicFileAttributes.class);
                    FileTime createTime = attributes.creationTime();
                    String dateFormat = df.format(createTime.toMillis());
                    TenantYqdaDocument document = new TenantYqdaDocument();
                    document.setTableName(category.getEfileTableName());
                    document.setDocId((Long) docData.get("DOC_ID"));
                    Map<String, String> updateDaoc = new HashMap<>();
                    updateDaoc.put("IS_IDENTIFICATION", "1");
                    updateDaoc.put("REAL_DOC_NAME", file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd");
                    updateDaoc.put("DOC_FILE_TYPE", "OFD");
                    updateDaoc.put("DOC_FILE_SIZE", ofdFile.length() + "");
                    //增加原路径
                    updateDaoc.put("DOC_PATH", docData.get("PATH").toString() );
                    updateDaoc.put("PATH", docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd");

                    updateDaoc.put("IDENTIFICATION_PATH", docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd");
                    updateDaoc.put("ACTION_TIME", dateFormat);
                    updateDaoc.put("UPDATE_TIME", df.format(new Date()));
                    updateDaoc.put("UPDATE_BY", SecurityUtils.getUserId() + "");
                    updateDaoc.put("DOC_NAME", docData.get("DOC_NAME").toString().substring(0, docData.get("DOC_NAME").toString().lastIndexOf(".")) + ".ofd");
                    //拿到SM3的hash 以及 MD5的hash
                    updateDaoc.put("FILE_ONLY_VAL", WebServiceFileUtils.getFileMD5(new File(docData.get("DOC_MNT").toString()+docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd")));
                    updateDaoc.put("FILE_ONLY_VAL_GM", EncryptionUtil.getSM3Hash(docData.get("DOC_MNT").toString()+docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd"));
                    document.setColNames(updateDaoc);
                    documentMapper.updateDocument(document);
                } else {
                    TenantYqdaDocument document = new TenantYqdaDocument();
                    document.setTableName(category.getEfileTableName());
                    document.setDocId((Long) docData.get("DOC_ID"));
                    Map<String, String> updateDaoc = new HashMap<>();
                    updateDaoc.put("IS_IDENTIFICATION", "2");
                    document.setColNames(updateDaoc);
                    documentMapper.updateDocument(document);
                    //文件识别错误原因
                    Long id = identificationRecord.getId();
                    IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, identificationRecord.getTableName());
                    identification.setTableName(identificationRecord.getTableName());
                    identification.setReason("调用识别接口失败！");
                    identificationRecordMapper.updateIdentificationRecord(identification);
                    throw new ServiceException("识别失败!,调用识别接口失败!");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ServiceException("识别失败！");
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void identifyHdyy(Long docId, Long categoryId) {
        //获取该值去验证
         DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        TenantCategory category = categoryMapper.selectTenantCategoryByID(categoryId,new TenantCategory().getTableName());
        Map<String, Object> docData = documentMapper.getDocumentMessageById("a.DOC_ID,a.PATH,a.DOC_FILE_TYPE,a.REAL_DOC_NAME,a.DOC_MNT,a.DOC_NAME,a.IS_IDENTIFICATION,b.DH,b.TITLE",docId,category.getEfileTableName(),category.getFileTableName());
        File file = new File(docData.get("DOC_MNT").toString()+docData.get("PATH").toString());
        String hz = docData.get("DOC_FILE_TYPE").toString().toLowerCase();
        if(docData.get("IS_IDENTIFICATION")!=null && "1".equals(docData.get("IS_IDENTIFICATION").toString())){
            throw new ServiceException("该文件已识别！");
        }
        String ocrFilesType = sysConfigService.selectConfigByKey("OCR_FILES_TYPE");
        if(StringUtils.isEmpty(ocrFilesType)){
            throw new  ServiceException("系统参数错误OCR_FILES_TYPE未找到配置！");
        }

        if((ocrFilesType+";").indexOf(hz+";")<0){
            throw new ServiceException("该文件格式不需要识别！");
        }
        String ocrFilesSize = sysConfigService.selectConfigByKey("OCR_FILES_SIZE");
        if(StringUtils.isEmpty(ocrFilesSize)){
            throw new  ServiceException("系统参数错误OCR_FILES_SIZE未找到配置！");
        }
        if(file.exists()) {
            double size = (double) file.length() / (1024 * 1024);
            if (size > Integer.parseInt(ocrFilesSize)) {

                throw new ServiceException("文件较大无法识别！");

            }
        }
        try {

          //原文件
          if(file.exists()){
              String ofdPath = file.getParent()+File.separator+"ocr"+File.separator+file.getName().substring(0,file.getName().lastIndexOf("."))+".pdf";
              //tif的存储地址
              String tifPath = file.getParent()+File.separator+"tif"+File.separator+file.getName().substring(0,file.getName().lastIndexOf("."))+".ofd";

              String path=docData.get("DOC_MNT").toString()+docData.get("PATH").toString();

              List<File> docFile = new ArrayList<>();
              docFile.add(file);
              IdentificationRecord identificationRecord=new IdentificationRecord();
              identificationRecord.setCreateTime(DateUtils.getNowDate());
              identificationRecord.setCreateId(SecurityUtils.getUserId());
              identificationRecord.setDocId(docId);
              identificationRecord.setFileName(docData.get("DOC_NAME").toString());
              identificationRecord.setFilePath(docData.get("PATH").toString());
              identificationRecord.setState("0");
              identificationRecord.setFilesNo(docData.get("DH") == null ? "" : docData.get("DH").toString());
              identificationRecord.setTitle(docData.get("TITLE") == null ? "" : docData.get("TITLE").toString());
              identificationRecord.setRealFileName(docData.get("REAL_DOC_NAME").toString());
              identificationRecordMapper.insertIdentificationRecord(identificationRecord);
            //获取到值去调用接口
              //if(FileWaterMark.check(path)&&(!FileWaterMark.PdfIsEncryption(path))) {

//                  if ("png".equals(hz)
//                          || "jpg".equals(hz)
//                          || "jpeg".equals(hz)
//                          || "bmp".equals(hz)) {
//                      //转换  入库
//                      ocrUtils.imageToOFD(file, ofdPath, pictureUrl);
//                  } else if ("tiff".equals(hz) || "tif".equals(hz)) {
//                      ofdAgent.imageToOFD(docFile, tifPath);
//                      file = new File(tifPath);
//                      ocrUtils.officeToOFD(file, ofdPath, ofdUrl);
//                  } else if ("pdf".equals(hz)
//                          || "ofd".equals(hz)) {
//                      ocrUtils.officeToOFD(file, ofdPath, ofdUrl);
//                  }
                  boolean isSuccess = true;
                  if("tif".equals(hz.toLowerCase())
                          || "tiff".equals(hz.toLowerCase())
                          || "png".equals(hz.toLowerCase())
                          || "jpg".equals(hz.toLowerCase())){
                      isSuccess = imageToOFD(docFile,ofdPath);
                  }else {
                      isSuccess = officesToOfd(docFile,ofdPath);
                  }
                  if(isSuccess){
                      //增加识别记录
                      Long id = identificationRecord.getId();
                      IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, new IdentificationRecord().getTableName());
                      identification.setState("1");
                      identification.setNewFilePath(docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                      identificationRecordMapper.updateIdentificationRecord(identification);
                      //修改文件  将原文件进行修改
                      //修改电子文件表
                      File ofdFile = new File(ofdPath);
                      Path path2 = Paths.get(ofdPath);
                      BasicFileAttributes attributes = Files.readAttributes(path2, BasicFileAttributes.class);
                      FileTime createTime = attributes.creationTime();
                      String dateFormat = df.format(createTime.toMillis());
                      TenantYqdaDocument document = new TenantYqdaDocument();
                      document.setTableName(category.getEfileTableName());
                      document.setDocId((Long) docData.get("DOC_ID"));
                      Map<String, String> updateDaoc = new HashMap<>();
                      updateDaoc.put("IS_IDENTIFICATION", "1");
                      updateDaoc.put("REAL_DOC_NAME", file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                      updateDaoc.put("DOC_FILE_TYPE", "PDF");
                      updateDaoc.put("DOC_FILE_SIZE", ofdFile.length() + "");
                      updateDaoc.put("PATH", docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                      updateDaoc.put("ACTION_TIME", dateFormat);
                      updateDaoc.put("UPDATE_TIME", df.format(new Date()));
                      updateDaoc.put("UPDATE_BY", SecurityUtils.getUserId() + "");
                      updateDaoc.put("DOC_NAME", docData.get("DOC_NAME").toString().substring(0, docData.get("DOC_NAME").toString().lastIndexOf(".")) + ".pdf");
                      document.setColNames(updateDaoc);
                      documentMapper.updateDocument(document);
                  }else{
                      TenantYqdaDocument document = new TenantYqdaDocument();
                      document.setTableName(category.getEfileTableName());
                      document.setDocId((Long) docData.get("DOC_ID"));
                      Map<String, String> updateDaoc = new HashMap<>();
                      updateDaoc.put("IS_IDENTIFICATION", "2");
                      document.setColNames(updateDaoc);
                      documentMapper.updateDocument(document);
                      //文件识别错误原因
                      Long id = identificationRecord.getId();
                      IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, identificationRecord.getTableName());
                      identification.setReason("调用识别接口失败！");
                      identification.setTableName(identificationRecord.getTableName());
                      identificationRecordMapper.updateIdentificationRecord(identification);
                  }

//              }else{
//                  TenantYqdaDocument document = new TenantYqdaDocument();
//                  document.setTableName(category.getEfileTableName());
//                  document.setDocId((Long) docData.get("DOC_ID"));
//                  Map<String, String> updateDaoc = new HashMap<>();
//                  updateDaoc.put("IS_IDENTIFICATION", "1");
//                  document.setColNames(updateDaoc);
//                  documentMapper.updateDocument(document);
//              }
          }
      }catch (Exception ex){
          logger.error(ex.getMessage(),ex);
          throw new ServiceException("识别失败！");
      }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String identifyPdf(Long docId, Long categoryId) {
        String line="";
        //获取该值去验证
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        TenantCategory category = categoryMapper.selectTenantCategoryByID(categoryId, new TenantCategory().getTableName());
        Map<String, Object> docData = documentMapper.getDocumentMessageById("a.DOC_ID,a.PATH,a.DOC_FILE_TYPE,a.REAL_DOC_NAME,a.DOC_MNT,a.DOC_NAME,a.IS_IDENTIFICATION,b.DH,b.TITLE", docId, category.getEfileTableName(), category.getFileTableName());

        File file = new File(docData.get("DOC_MNT").toString() + docData.get("PATH").toString());
        String hz = docData.get("DOC_FILE_TYPE").toString().toLowerCase();
        if (docData.get("IS_IDENTIFICATION") != null && "1".equals(docData.get("IS_IDENTIFICATION").toString())) {
            throw new ServiceException("该文件已识别！");
        }
        String ocrFilesType = sysConfigService.selectConfigByKey("OCR_FILES_TYPE");
        if (StringUtils.isEmpty(ocrFilesType)) {
            throw new ServiceException("系统参数错误OCR_FILES_TYPE未找到配置！");
        }

        if ((ocrFilesType + ";").indexOf(hz + ";") < 0) {
            throw new ServiceException("该文件格式不需要识别！");
        }
        String ocrFilesSize = sysConfigService.selectConfigByKey("OCR_FILES_SIZE");
        if (StringUtils.isEmpty(ocrFilesSize)) {
            throw new ServiceException("系统参数错误OCR_FILES_SIZE未找到配置！");
        }
        if (file.exists()) {
            double size = (double) file.length() / (1024 * 1024);
            if (size > Integer.parseInt(ocrFilesSize)) {

                throw new ServiceException("文件较大无法识别！");

            }
        }
        Long maxPdfSize = 0L;
        if ("1".equals(isZt)) {
            String pdfSize = sysConfigService.selectConfigByKey("MAX_PDF_SIZE");
            if (StringUtils.isEmpty(pdfSize)) {
                throw new ServiceException("系统参数错误MAX_PDF_SIZE未找到配置！");
            }
            maxPdfSize = Long.valueOf(pdfSize) * 1024 * 1024;
        }
        try {
            //原文件
            if (file.exists()) {
                String pdfPath = file.getParent() + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf";
                //tif的存储地址
                String tifPath = file.getParent() + File.separator + "tif" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd";
                String path = docData.get("DOC_MNT").toString() + docData.get("PATH").toString();

                List<File> docFile = new ArrayList<>();
                docFile.add(file);
                IdentificationRecord identificationRecord = new IdentificationRecord();
                identificationRecord.setCreateTime(DateUtils.getNowDate());
                identificationRecord.setCreateId(SecurityUtils.getUserId());
                identificationRecord.setDocId(docId);
                identificationRecord.setFileName(docData.get("DOC_NAME").toString());
                identificationRecord.setFilePath(docData.get("PATH").toString());
                identificationRecord.setState("0");
                identificationRecord.setFilesNo(docData.get("DH") == null ? "" : docData.get("DH").toString());
                identificationRecord.setTitle(docData.get("TITLE") == null ? "" : docData.get("TITLE").toString());

                identificationRecord.setRealFileName(docData.get("REAL_DOC_NAME").toString());
                identificationRecordMapper.insertIdentificationRecord(identificationRecord);
//                if(FileWaterMark.check(path)&&(!FileWaterMark.PdfIsEncryption(path))) {

                boolean flag1 = false;

                //获取到值去调用接口
                if ("png".equals(hz)
                        || "jpg".equals(hz)
                        || "jpeg".equals(hz)
                        || "bmp".equals(hz)) {
                    //转换  入库
                    flag1 = ocrUtils.imageToPDF(file, pdfPath, pictureUrl);
                } else if ("tiff".equals(hz) || "tif".equals(hz)) {
                    ofdAgent.imageToOFD(docFile, tifPath);
                    file = new File(tifPath);
                    flag1 = ocrUtils.officeToOFD(file, pdfPath, pdfUrl);
                } else if ("pdf".equals(hz)) {
                    if ("1".equals(isZt)) {
                        //中铁系统拿参数判断是否需要转图片
                        int count = PdfUtils.getPageCount(path);
                        if (count == 1 && file.length() > maxPdfSize) {
                            String imgPath = file.getParent() + File.separator + "img";
                            File file1 = new File(imgPath);
                            if (!file1.exists()) {
                                file1.mkdirs();
                            }
                            List<String> filePath = PdfUtils.pdf2Img(path, imgPath + File.separator);
                            //因为只有一页
                            if (filePath.size() > 0) {
                                File imgFile = new File(filePath.get(0));
                                if (imgFile.exists()) {
                                    flag1 = ocrUtils.imageToPDF(imgFile, pdfPath, pictureUrl);
                                } else {
                                    flag1 = false;
                                }
                            } else {
                                flag1 = false;
                            }
                        } else {
                            flag1 = ocrUtils.officeToOFD(file, pdfPath, pdfUrl);
                        }
                    } else {
                        flag1 = ocrUtils.officeToOFD(file, pdfPath, pdfUrl);
                    }
                } else if ("ofd".equals(hz)) {
                    flag1 = ocrUtils.officeToOFD(file, pdfPath, pdfUrl);
                }
                //增加识别记录
                if (flag1) {
                    Long id = identificationRecord.getId();
                    IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, new IdentificationRecord().getTableName());
                    identification.setTableName(identificationRecord.getTableName());
                    identification.setState("1");
                    identification.setNewFilePath(docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                    identificationRecordMapper.updateIdentificationRecord(identification);
                    //修改文件  将原文件进行修改
                    //修改电子文件表
                    File ofdFile = new File(pdfPath);
                    Path path2 = Paths.get(pdfPath);
                    BasicFileAttributes attributes = Files.readAttributes(path2, BasicFileAttributes.class);
                    FileTime createTime = attributes.creationTime();
                    String dateFormat = df.format(createTime.toMillis());
                    TenantYqdaDocument document = new TenantYqdaDocument();
                    document.setTableName(category.getEfileTableName());
                    document.setDocId((Long) docData.get("DOC_ID"));
                    Map<String, String> updateDaoc = new HashMap<>();
                    updateDaoc.put("IS_IDENTIFICATION", "1");
                    updateDaoc.put("REAL_DOC_NAME", file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                    updateDaoc.put("DOC_FILE_TYPE", "PDF");
                    updateDaoc.put("DOC_FILE_SIZE", ofdFile.length() + "");
                    updateDaoc.put("DOC_PATH", docData.get("PATH").toString() );
                    updateDaoc.put("PATH", docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                    updateDaoc.put("IDENTIFICATION_PATH", docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                    updateDaoc.put("ACTION_TIME", dateFormat);
                    updateDaoc.put("UPDATE_TIME", df.format(new Date()));
                    updateDaoc.put("UPDATE_BY", SecurityUtils.getUserId() + "");
                    updateDaoc.put("DOC_NAME", docData.get("DOC_NAME").toString().substring(0, docData.get("DOC_NAME").toString().lastIndexOf(".")) + ".pdf");
                    updateDaoc.put("FILE_ONLY_VAL", WebServiceFileUtils.getFileMD5(new File(docData.get("DOC_MNT").toString()+docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf")));
                    updateDaoc.put("FILE_ONLY_VAL_GM", EncryptionUtil.getSM3Hash(docData.get("DOC_MNT").toString()+docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf"));

                    document.setColNames(updateDaoc);
                    documentMapper.updateDocument(document);
                    line=PdfUtils.getPageLine(docData.get("DOC_MNT").toString() + File.separator+updateDaoc.get("IDENTIFICATION_PATH"));
                } else {
                    TenantYqdaDocument document = new TenantYqdaDocument();
                    document.setTableName(category.getEfileTableName());
                    document.setDocId((Long) docData.get("DOC_ID"));
                    Map<String, String> updateDaoc = new HashMap<>();
                    updateDaoc.put("IS_IDENTIFICATION", "2");
                    document.setColNames(updateDaoc);
                    documentMapper.updateDocument(document);
                    //文件识别错误原因
                    Long id = identificationRecord.getId();
                    IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, identificationRecord.getTableName());
                    identification.setReason("调用识别接口失败！");
                    identification.setTableName(identificationRecord.getTableName());
                    identificationRecordMapper.updateIdentificationRecord(identification);
                    throw new ServiceException("识别失败!调用识别接口失败!");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ServiceException("识别失败！");
        }
        return line;
    }


    @Override
    public void identifyTask(String tenantCode,String categoryId) {
        //定时转换成ofd
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            TenantCategory selectC = new TenantCategory();
            selectC.setTableName(tenantCode + TenantCategory.BIGTABLENAME);
            if(StringUtils.isNotEmpty(categoryId)){
                selectC.setCategoryId(Long.valueOf(categoryId));
            }
            List<TenantCategory> categoryList = categoryMapper.selectTenantCategoryList(selectC);
            String ocrFilesSize = sysConfigService.selectConfigByCode("OCR_FILES_SIZE", tenantCode);
            if (StringUtils.isEmpty(ocrFilesSize)) {
                throw new ServiceException("系统参数错误OCR_FILES_SIZE未找到配置！");
            }
            Long size = Long.valueOf(ocrFilesSize) * 1024 * 1024;
            Long maxPdfSize = 0L;
            if ("1".equals(isZt)) {
                String pdfSize = sysConfigService.selectConfigByCode("MAX_PDF_SIZE", tenantCode);
                if (StringUtils.isEmpty(pdfSize)) {
                    throw new ServiceException("系统参数错误MAX_PDF_SIZE未找到配置！");
                }
                maxPdfSize = Long.valueOf(pdfSize) * 1024 * 1024;
            }

            for (TenantCategory category : categoryList) {
                if (StringUtils.isNotEmpty(category.getEfileTableName()) && StringUtils.isNotEmpty(category.getFileTableName())) {
//                    Map<String,String> map = new HashMap<>();
//                    map.put("a.IS_DEL","0");
//                    map.put("a.DOC_FILE_TYPE","PDF");
                    //获取所有的已归档的附件pdf 归档 5
                    List<Map<String, Object>> docList = documentMapper.getAllDocByDaQuery("a.DOC_ID,a.PATH,a.DOC_FILE_TYPE,a.REAL_DOC_NAME,a.DOC_MNT,a.DOC_NAME,b.DH,b.TITLE,a.CON_TABLE_ID", " a.IS_DEL='0' and (a.DOC_FILE_TYPE='PDF' or a.DOC_FILE_TYPE='JPG' or a.DOC_FILE_TYPE='PNG' )  ", category.getEfileTableName(), category.getFileTableName(), size);
                    Map<String, List<Map<String, Object>>> daList = docList.stream().collect(Collectors.groupingBy(c -> c.get("CON_TABLE_ID").toString()));
                    //Map遍历
                    for (String key : daList.keySet()) {
                        List<Map<String, Object>> list = daList.get(key);
                        boolean indexFlag = false;
                        for (Map<String, Object> docData : list) {
                            File file = new File(docData.get("DOC_MNT").toString() + docData.get("PATH").toString());
                            String path = docData.get("DOC_MNT").toString() + docData.get("PATH").toString();
                            if (file.exists()) {
                                //添加转换记录
                                IdentificationRecord identificationRecord = new IdentificationRecord();
                                identificationRecord.setCreateTime(DateUtils.getNowDate());
                                identificationRecord.setTableName(tenantCode + IdentificationRecord.BIGTABLENAME);

                                // identificationRecord.setCreateId(SecurityUtils.getUserId());
                                identificationRecord.setDocId((Long) docData.get("DOC_ID"));
                                identificationRecord.setFileName(docData.get("DOC_NAME").toString());
                                identificationRecord.setFilePath(docData.get("PATH").toString());
                                identificationRecord.setState("0");
                                identificationRecord.setFilesNo(docData.get("DH") == null ? "" : docData.get("DH").toString());
                                identificationRecord.setTitle(docData.get("TITLE") == null ? "" : docData.get("TITLE").toString());
                                identificationRecord.setRealFileName(docData.get("REAL_DOC_NAME").toString());
                                identificationRecordMapper.insertIdentificationRecord(identificationRecord);

                                boolean flag = false;
                                boolean flag1 = false;

                                String hz = docData.get("DOC_FILE_TYPE").toString();
                                if ("pdf".equals(hz.toLowerCase())) {
                                    flag = FileWaterMark.check(path);
                                    flag1 = FileWaterMark.PdfIsEncryption(path);
                                } else if ("jpg".equals(hz.toLowerCase()) || "png".equals(hz.toLowerCase())) {
                                    //jpg，png
                                    flag = FileWaterMark.checkImage(path);
                                }
                                if (flag && (!flag1)) {
                                    TransactionStatus transactionStatus = null;
                                    transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
                                    try {

                                        //String hz = docData.get("DOC_FILE_TYPE").toString();
                                        String ofdPath = file.getParent() + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd";
//                                if (!new File(ofdPath).getParentFile().exists()) {
//                                    new File(ofdPath).getParentFile().mkdirs();
//                                }
                                        boolean flag2 = false;

                                        if ("pdf".equals(hz.toLowerCase())) {
                                            if ("1".equals(isZt)) {
                                                //中铁系统拿参数判断是否需要转图片
                                                int count = PdfUtils.getPageCount(path);
                                                if (count == 1 && file.length() > maxPdfSize) {
                                                    String imgPath = file.getParent() + File.separator + "img";
                                                    File file1 = new File(imgPath);
                                                    if (!file1.exists()) {
                                                        file1.mkdirs();
                                                    }
                                                    List<String> filePath = PdfUtils.pdf2Img(path, imgPath + File.separator);
                                                    //因为只有一页
                                                    if (filePath.size() > 0) {
                                                        File imgFile = new File(filePath.get(0));
                                                        if (imgFile.exists()) {
                                                            flag2 = ocrUtils.imageToOFD(imgFile, ofdPath, pictureUrl);
                                                        } else {
                                                            flag2 = false;
                                                        }
                                                    } else {
                                                        flag2 = false;
                                                    }
                                                } else {
                                                    flag2 = ocrUtils.officeToOFD(file, ofdPath, ofdUrl);

                                                }
                                            } else {
                                                flag2 = ocrUtils.officeToOFD(file, ofdPath, ofdUrl);
                                            }

                                        } else if ("jpg".equals(hz.toLowerCase()) || "png".equals(hz.toLowerCase())) {

                                            flag2 = ocrUtils.imageToOFD(file, ofdPath, pictureUrl);

                                        }
                                        //增加识别记录
                                        if (flag2&&new File(ofdPath).exists()&&new File(ofdPath).length()!=0) {
                                            indexFlag = true;
                                            Long id = identificationRecord.getId();
                                            IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, tenantCode + IdentificationRecord.BIGTABLENAME);
                                            identification.setTableName(tenantCode + IdentificationRecord.BIGTABLENAME);
                                            identification.setState("1");
                                            identification.setNewFilePath(docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd");
                                            identificationRecordMapper.updateIdentificationRecord(identification);
                                            //修改文件  将原文件进行修改
                                            //修改电子文件表
                                            File ofdFile = new File(ofdPath);
                                            Path path2 = Paths.get(ofdPath);
                                            BasicFileAttributes attributes = Files.readAttributes(path2, BasicFileAttributes.class);
                                            FileTime createTime = attributes.creationTime();
                                            String dateFormat = df.format(createTime.toMillis());
                                            TenantYqdaDocument document = new TenantYqdaDocument();
                                            document.setTableName(category.getEfileTableName());
                                            document.setDocId((Long) docData.get("DOC_ID"));
                                            Map<String, String> updateDaoc = new HashMap<>();
                                            updateDaoc.put("IS_IDENTIFICATION", "1");

                                            updateDaoc.put("REAL_DOC_NAME", file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd");
                                            updateDaoc.put("DOC_FILE_TYPE", "OFD");
                                            updateDaoc.put("DOC_FILE_SIZE", ofdFile.length() + "");
                                            updateDaoc.put("DOC_PATH", docData.get("PATH").toString() );
                                            updateDaoc.put("PATH", docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd");

                                            updateDaoc.put("IDENTIFICATION_PATH", docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd");
                                            updateDaoc.put("ACTION_TIME", dateFormat);
                                            updateDaoc.put("UPDATE_TIME", df.format(new Date()));
                                            // updateDaoc.put("UPDATE_BY",SecurityUtils.getUserId()+"");
                                            updateDaoc.put("DOC_NAME", docData.get("DOC_NAME").toString().substring(0, docData.get("DOC_NAME").toString().lastIndexOf(".")) + ".ofd");
                                            updateDaoc.put("FILE_ONLY_VAL", WebServiceFileUtils.getFileMD5(new File(docData.get("DOC_MNT").toString()+docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd")));
                                            updateDaoc.put("FILE_ONLY_VAL_GM", EncryptionUtil.getSM3Hash(docData.get("DOC_MNT").toString()+docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".ofd"));

                                            document.setColNames(updateDaoc);
                                            documentMapper.updateDocument(document);
                                        } else {
                                            TenantYqdaDocument document = new TenantYqdaDocument();
                                            document.setTableName(category.getEfileTableName());
                                            document.setDocId((Long) docData.get("DOC_ID"));
                                            Map<String, String> updateDaoc = new HashMap<>();
                                            updateDaoc.put("IS_IDENTIFICATION", "2");
                                            document.setColNames(updateDaoc);
                                            documentMapper.updateDocument(document);
                                            //文件识别错误原因
                                            Long id = identificationRecord.getId();
                                            IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, tenantCode + IdentificationRecord.BIGTABLENAME);
                                            identification.setTableName(tenantCode + IdentificationRecord.BIGTABLENAME);

                                            identification.setReason("调用识别接口失败！");
                                            identificationRecordMapper.updateIdentificationRecord(identification);
                                        }
                                        dataSourceTransactionManager.commit(transactionStatus);
                                    } catch (Exception e) {
                                        logger.error(e.getMessage(), e);
                                        if (transactionStatus != null) {
                                            dataSourceTransactionManager.rollback(transactionStatus);
                                        }
                                    }


                                } else {
                                    TenantYqdaDocument document = new TenantYqdaDocument();
                                    document.setTableName(category.getEfileTableName());
                                    document.setDocId((Long) docData.get("DOC_ID"));
                                    Map<String, String> updateDaoc = new HashMap<>();
                                    updateDaoc.put("IS_IDENTIFICATION", "1");
                                    document.setColNames(updateDaoc);
                                    documentMapper.updateDocument(document);
                                    //文件识别错误原因
                                    Long id = identificationRecord.getId();
                                    IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, tenantCode + IdentificationRecord.BIGTABLENAME);
                                    identification.setTableName(tenantCode + IdentificationRecord.BIGTABLENAME);
                                    identification.setReason("文件加密或受损！");
                                    identificationRecordMapper.updateIdentificationRecord(identification);
                                }
                            }
                        }
                        //修改附件的状态
                        if (StringUtils.isNotEmpty(key) && indexFlag) {
                            documentMapper.updateIndex(tenantCode, key);
                        }


                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }


    }

    public void identifyTaskHdyy(String tenantCode,String categoryId) {
        //定时转换成ofd
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            TenantCategory selectC = new TenantCategory();
            selectC.setTableName(tenantCode+ TenantCategory.BIGTABLENAME);
            if(StringUtils.isNotEmpty(categoryId)){
                selectC.setCategoryId(Long.valueOf(categoryId));
            }
            List<TenantCategory> categoryList = categoryMapper.selectTenantCategoryList(selectC);
            String ocrFilesSize = sysConfigService.selectConfigByCode("OCR_FILES_SIZE",tenantCode);
            if(StringUtils.isEmpty(ocrFilesSize)){
                throw new  ServiceException("系统参数错误OCR_FILES_SIZE未找到配置！");
            }
            Long size=Long.valueOf(ocrFilesSize)*1024*1024;


            for(TenantCategory category:categoryList){
                if(StringUtils.isNotEmpty(category.getEfileTableName())&&StringUtils.isNotEmpty(category.getFileTableName())){
//                    Map<String,String> map = new HashMap<>();
//                    map.put("a.IS_DEL","0");
//                    map.put("a.DOC_FILE_TYPE","PDF");
                    //获取所有的已归档的附件pdf 归档 5
                    List<Map<String,Object>> list = documentMapper.getAllDocByDaQuery("a.DOC_ID,a.PATH,a.DOC_FILE_TYPE,a.REAL_DOC_NAME,a.DOC_MNT,a.DOC_NAME,b.DH,b.TITLE"," a.IS_DEL='0' and (a.DOC_FILE_TYPE='PDF' or a.DOC_FILE_TYPE='JPG' or a.DOC_FILE_TYPE='PNG' )  ",category.getEfileTableName(),category.getFileTableName(),size);
                    for(Map<String,Object> docData:list){
                        File file = new File(docData.get("DOC_MNT").toString()+docData.get("PATH").toString());
                        String path=docData.get("DOC_MNT").toString()+docData.get("PATH").toString();
                        if(file.exists()) {
//                            Yqdatransdoc yqdatransdoc = new Yqdatransdoc();
//                            yqdatransdoc.setDocId((Long)docData.get("DOC_ID"));
//                            yqdatransdoc.setTransType("hdyyofdIdentify");
//                            yqdatransdoc.setState(0); //默认失败
//                            yqdatransdocMapper.insertYqdatransdoc(yqdatransdoc);
//                            List<File> docFile = new ArrayList<>();
//                            docFile.add(file);
//                            String hz = docData.get("DOC_FILE_TYPE").toString();
//                            String ofdPath = "";
//                            ofdPath = file.getParent()+File.separator+"pdf"+File.separator+file.getName().substring(0,file.getName().lastIndexOf("."))+".PDF";
//
//                            System.out.println("ofdPath="+ofdPath);
//                            if (!new File(ofdPath).getParentFile().exists()) {
//                                new File(ofdPath).getParentFile().mkdirs();
//                            }
//                            if("tif".equals(hz.toLowerCase())
//                                    || "tiff".equals(hz.toLowerCase())
//                                    || "png".equals(hz.toLowerCase())
//                                    || "jpg".equals(hz.toLowerCase())){
//                                imageToOFD(docFile,ofdPath);
//                            }else {
//                                officesToOfd(docFile,ofdPath);
//                            }
//                            saveHdyy(yqdatransdoc.getTransId(),file.getName(),docData,category,SecurityUtils.getTenantCode());



                            //添加转换记录
                            IdentificationRecord identificationRecord = new IdentificationRecord();
                            identificationRecord.setCreateTime(DateUtils.getNowDate());
                            identificationRecord.setTableName(tenantCode + IdentificationRecord.BIGTABLENAME);

                            // identificationRecord.setCreateId(SecurityUtils.getUserId());
                            identificationRecord.setDocId((Long) docData.get("DOC_ID"));
                            identificationRecord.setFileName(docData.get("DOC_NAME").toString());
                            identificationRecord.setFilePath(docData.get("PATH").toString());
                            identificationRecord.setState("0");
                            identificationRecord.setFilesNo(docData.get("DH") == null ? "" : docData.get("DH").toString());
                            identificationRecord.setTitle(docData.get("TITLE") == null ? "" : docData.get("TITLE").toString());
                            identificationRecord.setRealFileName(docData.get("REAL_DOC_NAME").toString());
                            identificationRecordMapper.insertIdentificationRecord(identificationRecord);

                            boolean flag=false;
                            boolean flag1=false;

                            String hz = docData.get("DOC_FILE_TYPE").toString();
//                            if("pdf".equals(hz.toLowerCase())){
//                                flag=FileWaterMark.check(path);
//                                flag1=FileWaterMark.PdfIsEncryption(path);
//                            }else if("jpg".equals(hz.toLowerCase())||"png".equals(hz.toLowerCase())) {
//                                //jpg，png
//                                flag=FileWaterMark.checkImage(path);
//                            }
                            //if(flag&&(!flag1)) {
                                TransactionStatus transactionStatus = null;
                                transactionStatus =dataSourceTransactionManager.getTransaction(transactionDefinition);
                                List<File> docFile = new ArrayList<>();
                                docFile.add(file);
                                //String hz = docData.get("DOC_FILE_TYPE").toString();
                                String ofdPath = file.getParent() + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf";
//                                if (!new File(ofdPath).getParentFile().exists()) {
//                                    new File(ofdPath).getParentFile().mkdirs();
//                                }
                                try {
                                    boolean isSuccess = true;
                                    if("tif".equals(hz.toLowerCase())
                                            || "tiff".equals(hz.toLowerCase())
                                            || "png".equals(hz.toLowerCase())
                                            || "jpg".equals(hz.toLowerCase())){
                                        isSuccess = imageToOFD(docFile,ofdPath);

                                    }else {
                                        isSuccess = officesToOfd(docFile,ofdPath);
                                    }
                                    if(isSuccess){
                                        //增加识别记录
                                        Long id = identificationRecord.getId();
                                        IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, tenantCode + IdentificationRecord.BIGTABLENAME);
                                        identification.setTableName(tenantCode + IdentificationRecord.BIGTABLENAME);
                                        identification.setState("1");
                                        identification.setNewFilePath(docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                                        identificationRecordMapper.updateIdentificationRecord(identification);
                                        //修改文件  将原文件进行修改
                                        //修改电子文件表
                                        File ofdFile = new File(ofdPath);
                                        Path path2 = Paths.get(ofdPath);
                                        BasicFileAttributes attributes = Files.readAttributes(path2, BasicFileAttributes.class);
                                        FileTime createTime = attributes.creationTime();
                                        String dateFormat = df.format(createTime.toMillis());
                                        TenantYqdaDocument document = new TenantYqdaDocument();
                                        document.setTableName(category.getEfileTableName());
                                        document.setDocId((Long) docData.get("DOC_ID"));
                                        Map<String, String> updateDaoc = new HashMap<>();
                                        updateDaoc.put("IS_IDENTIFICATION", "1");
                                        updateDaoc.put("REAL_DOC_NAME", file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                                        updateDaoc.put("DOC_FILE_TYPE", "PDF");
                                        updateDaoc.put("DOC_FILE_SIZE", ofdFile.length() + "");
                                        updateDaoc.put("PATH", docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                                        updateDaoc.put("ACTION_TIME", dateFormat);
                                        updateDaoc.put("UPDATE_TIME", df.format(new Date()));
                                        // updateDaoc.put("UPDATE_BY",SecurityUtils.getUserId()+"");
                                        updateDaoc.put("DOC_NAME", docData.get("DOC_NAME").toString().substring(0, docData.get("DOC_NAME").toString().lastIndexOf(".")) + ".pdf");
                                        document.setColNames(updateDaoc);
                                        documentMapper.updateDocument(document);
                                    }else{
                                        TenantYqdaDocument document = new TenantYqdaDocument();
                                        document.setTableName(category.getEfileTableName());
                                        document.setDocId((Long) docData.get("DOC_ID"));
                                        Map<String, String> updateDaoc = new HashMap<>();
                                        updateDaoc.put("IS_IDENTIFICATION", "2");
                                        document.setColNames(updateDaoc);
                                        documentMapper.updateDocument(document);
                                        //文件识别错误原因
                                        Long id = identificationRecord.getId();
                                        IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, tenantCode + IdentificationRecord.BIGTABLENAME);
                                        identification.setTableName(tenantCode + IdentificationRecord.BIGTABLENAME);

                                        identification.setReason("调用识别接口失败！");
                                        identificationRecordMapper.updateIdentificationRecord(identification);
                                    }

                                    dataSourceTransactionManager.commit(transactionStatus);

                                } catch (Exception e) {
                                    logger.error(e.getMessage(), e);
                                    if (transactionStatus != null) {
                                        dataSourceTransactionManager.rollback(transactionStatus);
                                    }
                                }
//                            }else{
//                                TenantYqdaDocument document = new TenantYqdaDocument();
//                                document.setTableName(category.getEfileTableName());
//                                document.setDocId((Long) docData.get("DOC_ID"));
//                                Map<String, String> updateDaoc = new HashMap<>();
//                                updateDaoc.put("IS_IDENTIFICATION", "1");
//                                document.setColNames(updateDaoc);
//                                documentMapper.updateDocument(document);
//                            }
                        }
                  }
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public void identifyPdfTask(String tenantCode,String categoryId) {
        //定时转换成pdf
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            TenantCategory selectC = new TenantCategory();
            selectC.setTableName(tenantCode + TenantCategory.BIGTABLENAME);
            if(StringUtils.isNotEmpty(categoryId)){
              selectC.setCategoryId(Long.valueOf(categoryId));
            }
            List<TenantCategory> categoryList = categoryMapper.selectTenantCategoryList(selectC);
            String ocrFilesSize = sysConfigService.selectConfigByCode("OCR_FILES_SIZE", tenantCode);
            if (StringUtils.isEmpty(ocrFilesSize)) {
                throw new ServiceException("系统参数错误OCR_FILES_SIZE未找到配置！");
            }
            Long size = Long.valueOf(ocrFilesSize) * 1024 * 1024;

            Long maxPdfSize = 0L;
            if ("1".equals(isZt)) {
                String pdfSize = sysConfigService.selectConfigByCode("MAX_PDF_SIZE", tenantCode);
                if (StringUtils.isEmpty(pdfSize)) {
                    throw new ServiceException("系统参数错误MAX_PDF_SIZE未找到配置！");
                }
                maxPdfSize = Long.valueOf(pdfSize) * 1024 * 1024;
            }

            for (TenantCategory category : categoryList) {
                if (StringUtils.isNotEmpty(category.getEfileTableName()) && StringUtils.isNotEmpty(category.getFileTableName())) {
                    //  Map<String,String> map = new HashMap<>();
                    //Jpg，png
                    //map.put("a.IS_DEL","0");
                    //map.put("a.DOC_FILE_TYPE","PDF");
                    //获取所有的已归档的附件pdf 归档 5   A001_001_TESTISOPENSJIAN_0_E_A "ZTSJZGS_28_WS_1_E_A","ZTSJZGS_28_WS_1_F_A"
                    List<Map<String, Object>> docList = documentMapper.getAllDocByDaQuery("a.DOC_ID,a.PATH,a.DOC_FILE_TYPE,a.REAL_DOC_NAME,a.DOC_MNT,a.DOC_NAME,b.DH,b.TITLE,a.CON_TABLE_ID", " a.IS_DEL='0' and (a.DOC_FILE_TYPE='PDF' or a.DOC_FILE_TYPE='JPG' or a.DOC_FILE_TYPE='PNG' )  ", category.getEfileTableName(), category.getFileTableName(), size);
                    Map<String, List<Map<String, Object>>> daList = docList.stream().collect(Collectors.groupingBy(c -> c.get("CON_TABLE_ID").toString()));
                    //Map遍历
                    for (String key : daList.keySet()) {
                        List<Map<String, Object>> list = daList.get(key);
                        boolean indexFlag = false;
                        for (Map<String, Object> docData : list) {
                            File file = new File(docData.get("DOC_MNT").toString() + docData.get("PATH").toString());
                            String path = docData.get("DOC_MNT").toString() + docData.get("PATH").toString();

                            if (file.exists()) {

                                IdentificationRecord identificationRecord = new IdentificationRecord();
                                identificationRecord.setTableName(tenantCode + IdentificationRecord.BIGTABLENAME);

                                identificationRecord.setCreateTime(DateUtils.getNowDate());
                                // identificationRecord.setCreateId(SecurityUtils.getUserId());
                                identificationRecord.setDocId((Long) docData.get("DOC_ID"));
                                identificationRecord.setFileName(docData.get("DOC_NAME").toString());
                                identificationRecord.setFilePath(docData.get("PATH").toString());
                                identificationRecord.setState("0");
                                identificationRecord.setFilesNo(docData.get("DH") == null ? "" : docData.get("DH").toString());
                                identificationRecord.setTitle(docData.get("TITLE") == null ? "" : docData.get("TITLE").toString());
                                identificationRecord.setRealFileName(docData.get("REAL_DOC_NAME").toString());
                                identificationRecordMapper.insertIdentificationRecord(identificationRecord);
                                boolean flag = false;
                                boolean flag1 = false;

                                String hz = docData.get("DOC_FILE_TYPE").toString();
                                if ("pdf".equals(hz.toLowerCase())) {
                                    flag = FileWaterMark.check(path);
                                    flag1 = FileWaterMark.PdfIsEncryption(path);
                                } else if ("jpg".equals(hz.toLowerCase()) || "png".equals(hz.toLowerCase())) {
                                    //jpg，png
                                    flag = FileWaterMark.checkImage(path);
                                }
                                if (flag && (!flag1)) {
                                    TransactionStatus transactionStatus = null;
                                    transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);


                                    try {

                                        String pdfPath = file.getParent() + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf";
                                        boolean flag2 = false;
                                        if ("pdf".equals(hz.toLowerCase())) {
                                            //判断pdf大小，如果pdf较大需要转成图片
                                            //  List<String> imgPdfList = PdfUtils.pdf2Img(url, cutPdfPath);
                                            if ("1".equals(isZt)) {
                                                //中铁系统拿参数判断是否需要转图片
                                                int count = PdfUtils.getPageCount(path);
                                                if (count == 1 && file.length() > maxPdfSize) {
                                                    String imgPath = file.getParent() + File.separator + "img";
                                                    File file1 = new File(imgPath);
                                                    if (!file1.exists()) {
                                                        file1.mkdirs();
                                                    }
                                                    List<String> filePath = PdfUtils.pdf2Img(path, imgPath + File.separator);
                                                    //因为只有一页
                                                    if (filePath.size() > 0) {
                                                        File imgFile = new File(filePath.get(0));
                                                        if (imgFile.exists()) {
                                                            flag2 = ocrUtils.imageToPDF(imgFile, pdfPath, pictureUrl);
                                                        } else {
                                                            flag2 = false;
                                                        }
                                                    } else {
                                                        flag2 = false;
                                                    }
                                                } else {
                                                    flag2 = ocrUtils.officeToOFD(file, pdfPath, pdfUrl);
                                                }
                                            } else {
                                                flag2 = ocrUtils.officeToOFD(file, pdfPath, pdfUrl);
                                            }

                                        } else if ("jpg".equals(hz.toLowerCase()) || "png".equals(hz.toLowerCase())) {

                                            flag2 = ocrUtils.imageToPDF(file, pdfPath, pictureUrl);

                                        }
                                        //增加识别记录
                                        if (flag2&&new File(pdfPath).exists()&&new File(pdfPath).length()!=0) {
                                            indexFlag = true;
                                            Long id = identificationRecord.getId();
                                            IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, tenantCode + IdentificationRecord.BIGTABLENAME);
                                            identification.setTableName(tenantCode + IdentificationRecord.BIGTABLENAME);
                                            identification.setState("1");
                                            identification.setNewFilePath(docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                                            identificationRecordMapper.updateIdentificationRecord(identification);
                                            //修改文件  将原文件进行修改
                                            //修改电子文件表
                                            File ofdFile = new File(pdfPath);
                                            Path path2 = Paths.get(pdfPath);
                                            BasicFileAttributes attributes = Files.readAttributes(path2, BasicFileAttributes.class);
                                            FileTime createTime = attributes.creationTime();
                                            String dateFormat = df.format(createTime.toMillis());
                                            TenantYqdaDocument document = new TenantYqdaDocument();
                                            document.setTableName(category.getEfileTableName());
                                            document.setDocId((Long) docData.get("DOC_ID"));
                                            Map<String, String> updateDaoc = new HashMap<>();
                                            updateDaoc.put("IS_IDENTIFICATION", "1");

                                            updateDaoc.put("REAL_DOC_NAME", file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                                            updateDaoc.put("DOC_FILE_TYPE", "PDF");
                                            updateDaoc.put("DOC_FILE_SIZE", ofdFile.length() + "");
                                            updateDaoc.put("DOC_PATH", docData.get("PATH").toString() );
                                            updateDaoc.put("PATH", docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");

                                            updateDaoc.put("IDENTIFICATION_PATH", docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf");
                                            updateDaoc.put("ACTION_TIME", dateFormat);
                                            updateDaoc.put("UPDATE_TIME", df.format(new Date()));
                                            //  updateDaoc.put("UPDATE_BY",SecurityUtils.getUserId()+"");
                                            updateDaoc.put("DOC_NAME", docData.get("DOC_NAME").toString().substring(0, docData.get("DOC_NAME").toString().lastIndexOf(".")) + ".pdf");
                                            updateDaoc.put("FILE_ONLY_VAL", WebServiceFileUtils.getFileMD5(new File(docData.get("DOC_MNT").toString()+docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf")));
                                            updateDaoc.put("FILE_ONLY_VAL_GM", EncryptionUtil.getSM3Hash(docData.get("DOC_MNT").toString()+docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator)) + File.separator + "ocr" + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".pdf"));

                                            document.setColNames(updateDaoc);
                                            documentMapper.updateDocument(document);


                                        } else {
                                            TenantYqdaDocument document = new TenantYqdaDocument();
                                            document.setTableName(category.getEfileTableName());
                                            document.setDocId((Long) docData.get("DOC_ID"));
                                            Map<String, String> updateDaoc = new HashMap<>();
                                            updateDaoc.put("IS_IDENTIFICATION", "2");
                                            document.setColNames(updateDaoc);
                                            documentMapper.updateDocument(document);
                                            //文件识别错误原因
                                            Long id = identificationRecord.getId();
                                            IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, tenantCode + IdentificationRecord.BIGTABLENAME);
                                            identification.setTableName(tenantCode + IdentificationRecord.BIGTABLENAME);

                                            identification.setReason("调用识别接口失败！");
                                            identificationRecordMapper.updateIdentificationRecord(identification);
                                        }
                                        dataSourceTransactionManager.commit(transactionStatus);

                                    } catch (Exception e) {
                                        logger.error(e.getMessage(), e);
                                        if (transactionStatus != null) {
                                            dataSourceTransactionManager.rollback(transactionStatus);
                                        }
                                    }

                                } else {
                                    TenantYqdaDocument document = new TenantYqdaDocument();
                                    document.setTableName(category.getEfileTableName());
                                    document.setDocId((Long) docData.get("DOC_ID"));
                                    Map<String, String> updateDaoc = new HashMap<>();
                                    updateDaoc.put("IS_IDENTIFICATION", "1");
                                    document.setColNames(updateDaoc);
                                    documentMapper.updateDocument(document);
                                    //文件识别错误原因
                                    Long id = identificationRecord.getId();
                                    IdentificationRecord identification = identificationRecordMapper.selectIdentificationRecordById(id, tenantCode + IdentificationRecord.BIGTABLENAME);
                                    identification.setTableName(tenantCode + IdentificationRecord.BIGTABLENAME);
                                    identification.setReason("文件加密或受损！");
                                    identificationRecordMapper.updateIdentificationRecord(identification);
                                }
                            }
                        }
                        //修改附件的状态
                        if (StringUtils.isNotEmpty(key) && indexFlag) {
                            documentMapper.updateIndex(tenantCode, key);
                        }
                        // System.out.println("Key = " + key + ", Value = " + map.get(key));
                    }
                }
            }
            //  System.out.println("12");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public void identifyTaskAll(String tenantCode,String categoryId) {
        String ishdyyofd = sysConfigService.selectConfigByCode("ISHDYYOFD",tenantCode);
        if("true".equalsIgnoreCase(ishdyyofd)){
            identifyTaskHdyy(tenantCode,categoryId);
        }else{
            if("pdf".equals(identifyType)) {
                identifyPdfTask(tenantCode,categoryId);
            }else{
                identifyTask(tenantCode,categoryId);
            }
        }

    }


    private void save(Long transId, String fileName, Map<String,Object> docData, TenantCategory category, String tenantCode){
        TransactionStatus transactionStatus = null;
        try {
            //手动开启事务
            transactionStatus =dataSourceTransactionManager.getTransaction(transactionDefinition);
            //修改电子文件表
            if(!"OCR".equalsIgnoreCase(transType)){
                TenantYqdaDocument document = new TenantYqdaDocument();
                document.setTableName(category.getEfileTableName());
                document.setDocId((Long) docData.get("DOC_ID"));
                Map<String,String> updateDaoc = new HashMap<>();
                updateDaoc.put("TO_OFD","1");
                document.setColNames(updateDaoc);
                documentMapper.updateDocument(document);
            }

            //添加转换记录
            Yqdatransdoc yqdatransdoc = new Yqdatransdoc();
            yqdatransdoc.setTransId(transId);
            //yqdatransdoc.setDocId((Long) docData.get("DOC_ID"));
            String transUrl = "";
            if("OCR".equalsIgnoreCase(transType)){
                transUrl = docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator))
                        +File.separator+ "pdf"+File.separator
                        +fileName.substring(0, fileName.lastIndexOf(".")) + ".PDF";
            }else{
                transUrl = docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator))
                        +File.separator+ "ofd"+File.separator
                        +fileName.substring(0, fileName.lastIndexOf(".")) + ".OFD";
            }
            yqdatransdoc.setTransUrl(transUrl);
            yqdatransdoc.setState(1);
            //yqdatransdoc.setTransType(transType);
            yqdatransdoc.setTableName(tenantCode+Yqdatransdoc.BIGTABLENAME);
            /*Long [] docId = new Long[]{yqdatransdoc.getDocId()};
            yqdatransdocMapper.delYqdatransdoc(yqdatransdoc.getTableName(),docId);*/
            yqdatransdocMapper.updateYqdatransdoc(yqdatransdoc);
            dataSourceTransactionManager.commit(transactionStatus);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            if (transactionStatus != null) {
                dataSourceTransactionManager.rollback(transactionStatus);
            }
        }

    }

    private void saveHdyy(Long transId, String fileName, Map<String,Object> docData, TenantCategory category, String tenantCode){
        TransactionStatus transactionStatus = null;
        try {
            //手动开启事务
            transactionStatus =dataSourceTransactionManager.getTransaction(transactionDefinition);
            //修改电子文件表
//            if(!"OCR".equalsIgnoreCase(transType)){
//                TenantYqdaDocument document = new TenantYqdaDocument();
//                document.setTableName(category.getEfileTableName());
//                document.setDocId((Long) docData.get("DOC_ID"));
//                Map<String,String> updateDaoc = new HashMap<>();
//                updateDaoc.put("TO_OFD","1");
//                document.setColNames(updateDaoc);
//                documentMapper.updateDocument(document);
//            }

            //添加转换记录
            Yqdatransdoc yqdatransdoc = new Yqdatransdoc();
            yqdatransdoc.setTransId(transId);
            //yqdatransdoc.setDocId((Long) docData.get("DOC_ID"));
            String transUrl = "";
            transUrl = docData.get("PATH").toString().substring(0, docData.get("PATH").toString().lastIndexOf(File.separator))
                    +File.separator+ "pdf"+File.separator
                    +fileName.substring(0, fileName.lastIndexOf(".")) + ".PDF";
            yqdatransdoc.setTransUrl(transUrl);
            yqdatransdoc.setState(1);
            //yqdatransdoc.setTransType(transType);
            yqdatransdoc.setTableName(tenantCode+Yqdatransdoc.BIGTABLENAME);
            /*Long [] docId = new Long[]{yqdatransdoc.getDocId()};
            yqdatransdocMapper.delYqdatransdoc(yqdatransdoc.getTableName(),docId);*/
            yqdatransdocMapper.updateYqdatransdoc(yqdatransdoc);
            dataSourceTransactionManager.commit(transactionStatus);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            if (transactionStatus != null) {
                dataSourceTransactionManager.rollback(transactionStatus);
            }
        }

    }


    public boolean officesToOfd(List<File> fileList, String outPath) throws Exception {
        boolean isSuccess = true;
        String SINGLETOMULTPATH = sysConfigService.selectConfigByKey("SINGLETOMULTPATH");
        if(!StringUtils.isNotEmpty(SINGLETOMULTPATH) || "null".equalsIgnoreCase(SINGLETOMULTPATH)){
            throw new ServiceException("ocr插件路径未配置");
        }
        logger.info("OCRAgent:officesToOfd=outPath1:"+outPath);
        outPath=outPath.substring(0, outPath.lastIndexOf(File.separator)-3)+"ocr"+File.separator+outPath.substring(outPath.lastIndexOf(File.separator)+1).substring(0,outPath.substring(outPath.lastIndexOf(File.separator)+1).lastIndexOf("."))+".pdf";
        logger.info("OCRAgent:officesToOfd=outPath2:"+outPath);
        if(!new File(outPath).exists()) {
            if(!new File(outPath).getParentFile().exists()) {
                new File(outPath).getParentFile().mkdirs();
            }
            // ocr 插件路径
            String ocrPath = SINGLETOMULTPATH;
            try{
                ProcessBuilder pb = new ProcessBuilder();
                File d = new File(ocrPath.substring(0, ocrPath.lastIndexOf(File.separator)));
                pb.directory(d);
                String path = fileList.get(0).getPath();
                pb.command(ocrPath,path,outPath,"300");
                Process p=pb.start();
                p.waitFor();
            }catch(Exception e){
                isSuccess = false;
                e.printStackTrace();
                //throw e;
            }
        }
        return isSuccess;
    }

    public boolean imageToOFD(List<File> filesList, String outPath) throws Exception {
        boolean isSuccess = true;
        String SINGLETOMULTPATH = sysConfigService.selectConfigByKey("SINGLETOMULTPATH");
        if(!StringUtils.isNotEmpty(SINGLETOMULTPATH) || "null".equalsIgnoreCase(SINGLETOMULTPATH)){
            throw new ServiceException("ocr插件路径未配置");
        }
        logger.info("OCRAgent:imageToOFD=outPath:"+outPath);
        outPath=outPath.substring(0, outPath.lastIndexOf(File.separator)-3)+"ocr"+File.separator+outPath.substring(outPath.lastIndexOf(File.separator)+1).substring(0,outPath.substring(outPath.lastIndexOf(File.separator)+1).lastIndexOf("."))+".pdf";
        if(!new File(outPath).exists()) {
            if(!new File(outPath).getParentFile().exists()) {
                new File(outPath).getParentFile().mkdirs();
            }
            // ocr 插件路径
            String ocrPath = SINGLETOMULTPATH;
            try{
                ProcessBuilder pb = new ProcessBuilder();
                File d = new File(ocrPath.substring(0, ocrPath.lastIndexOf(File.separator)));
                pb.directory(d);
                String path = filesList.get(0).getPath();
                pb.command(ocrPath,path,outPath,"300");
                Process p=pb.start();
                p.waitFor();
            }catch(Exception e){
                isSuccess = false;
                e.printStackTrace();
                //throw e;
            }
        }
        return isSuccess;
    }
}
